import 'dart:ui';
import 'dart:math';

import 'package:animated_transitions/animated_transitions.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:gradient_borders/gradient_borders.dart';
import 'package:vamos/view/question/social_detail_page.dart';
import 'package:vamos/view/chat/private_chat_page.dart';
import '../../core/index.dart';
import '../../core/widgets/report_dialog.dart';

/// 他人主页
class VamosOtherProfileInterface extends StatefulWidget {
  final UserDataEntity user;
  const VamosOtherProfileInterface({super.key, required this.user});

  @override
  State<VamosOtherProfileInterface> createState() =>
      _VamosOtherProfileInterfaceState();
}

class _VamosOtherProfileInterfaceState extends State<VamosOtherProfileInterface>
    with TickerProviderStateMixin {
  late TabController _tabController;
  int _selectedTabIndex = 0;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      setState(() {
        _selectedTabIndex = _tabController.index;
      });
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, AppState>(
      converter: (store) => store.state,
      builder: (context, state) {
        return Scaffold(
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my_background.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: _buildProfileContent(state),
          ).safeArea(top: false, bottom: false),
        );
      },
    );
  }

  Widget _buildProfileContent(AppState state) {
    return _buildProfileInterface(widget.user);
  }

  /// 构建个人页面界面
  Widget _buildProfileInterface(UserDataEntity user) {
    return Stack(
      children: [
        SingleChildScrollView(
          child: Column(
            children: [
              // 状态栏占位
              SizedBox(height: MediaQuery.of(context).padding.top + 35.h),

              // 个人资料头部
              _buildProfileHeader(user),

              // 内容标签页
              _buildContentTabs(),

              // 内容区域
              _buildContentArea(),

              // 底部间距
              SizedBox(height: 120.h),
            ],
          ),
        ),

        // 顶部导航栏
        _buildTopNavigationBar(),
      ],
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Positioned(
      top: MediaQuery.of(context).padding.top,
      left: 0,
      right: 0,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // 返回按钮
            Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.3),
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.arrow_back,
                size: 26.w,
                color: Colors.white,
              ).center().inkWell(
                onTap: () {
                  Navigator.of(context).pop();
                },
              ),
            ),

            // 信息按钮
            Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.3),
                shape: BoxShape.circle,
              ),
              child: Image.asset(
                'assets/images/report.png',
                width: 24.w,
                height: 24.w,
              ).center().inkWell(
                onTap: () {
                  _navigateToSettings();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 跳转到设置页面
  void _navigateToSettings() {
    // TODO: 实现设置页面跳转
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('Settings page coming soon'),
        duration: Duration(seconds: 2),
      ),
    );
  }

  /// 处理聊天操作
  void _handleChatAction(UserDataEntity user) async {
    final store = StoreProvider.of<AppState>(context);
    final currentUser = store.state.userState.activeUser;

    if (currentUser == null) {
      VamosLoginRequiredDialog.showLoginRequiredDialog(context);
      return;
    }

    // 检查是否是自己
    if (currentUser.uniqueId == user.uniqueId) {
      NotificationUtils.showError(
        context,
        message: 'Cannot chat with yourself',
      );
      return;
    }

    try {
      final chatManager = serviceLocator<ReduxChatManager>();

      // 检查是否已存在与目标用户的对话
      final existingConversation = _findExistingConversation(
        chatManager.getAllConversations(),
        currentUser.uniqueId,
        user.uniqueId,
      );

      // 跳转到聊天页面
      Navigator.of(context).push(
        TransitionPageRoute(
          builder:
              (context) => StoreProvider<AppState>(
                store: store,
                child: VamosPrivateChatInterface(
                  targetUser: user,
                  conversationId: existingConversation?.conversationId,
                ),
              ),
          transitionAnimation: BrushStrokeTransition(
            direction: TransitionDirection.right,
            colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
          ),
        ),
      );
    } catch (e) {
      NotificationUtils.showError(context, message: 'Error opening chat: $e');
    }
  }

  /// 查找现有对话
  ChatConversationEntity? _findExistingConversation(
    List<ChatConversationEntity> conversations,
    String currentUserId,
    String targetUserId,
  ) {
    for (final conversation in conversations) {
      // 检查是否是与目标用户的对话
      if (conversation.participantId == targetUserId) {
        return conversation;
      }
    }
    return null;
  }

  /// 处理关注操作
  void _handleFollowAction(
    UserDataEntity user,
    bool isCurrentlyFollowing,
  ) async {
    final store = StoreProvider.of<AppState>(context);
    final currentUser = store.state.userState.activeUser;

    if (currentUser == null) {
      VamosLoginRequiredDialog.showLoginRequiredDialog(context);
      return;
    }

    try {
      final followManager = serviceLocator<ReduxFollowManager>();

      if (isCurrentlyFollowing) {
        // 取消关注
        final success = await followManager.unfollowUser(
          currentUser.uniqueId,
          user.uniqueId,
        );
        if (success) {
          NotificationUtils.showSuccess(
            context,
            message: 'Unfollowed ${user.displayName}',
          );
        } else {
          NotificationUtils.showError(
            context,
            message: 'Failed to unfollow user',
          );
        }
      } else {
        // 关注用户
        final success = await followManager.followUser(
          currentUser.uniqueId,
          user.uniqueId,
        );
        if (success) {
          NotificationUtils.showSuccess(
            context,
            message: 'Following ${user.displayName}',
          );
        } else {
          NotificationUtils.showError(
            context,
            message: 'Failed to follow user',
          );
        }
      }
    } catch (e) {
      NotificationUtils.showError(context, message: 'Error: $e');
    }
  }

  /// 构建个人资料头部
  Widget _buildProfileHeader(UserDataEntity user) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 20.h),
      child: Column(
        children: [
          // 头像和用户信息
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 头像
              Container(
                width: 88.w,
                height: 88.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: GradientBoxBorder(
                    width: 2.w,
                    gradient: LinearGradient(
                      colors: [
                        Color(0xFF83BE4A),
                        Color(0xFFFB894E),
                        Color(0xFFE91E63),
                      ],
                    ),
                  ),
                ),
                child: Container(
                  width: 80.w,
                  height: 80.w,
                  margin: EdgeInsets.all(4.w), // 边框和头像之间的间距
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: Colors.transparent,
                  ),
                  child: ClipOval(
                    child:
                        user.profileImage.isNotEmpty
                            ? Image.asset(
                              user.profileImage,
                              width: 76.w,
                              height: 76.w,
                              fit: BoxFit.cover,
                            )
                            : Icon(
                              Icons.person,
                              size: 40.w,
                              color: Colors.white,
                            ).center(),
                  ),
                ),
              ),

              SizedBox(width: 20.w),

              // 用户信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 用户名
                    Text(
                      user.displayName,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 24.sp,
                        fontWeight: FontWeight.w700,
                        fontFamily:
                            GoogleFonts.poppins(
                              fontWeight: FontWeight.w700,
                            ).fontFamily,
                      ),
                    ),

                    SizedBox(height: 8.h),

                    // 个人简介
                    Text(
                      user.personalBio.isNotEmpty
                          ? user.personalBio
                          : 'Deep skateboard enthusiasts, those who like it can join forces',
                      style: TextStyle(
                        color: Colors.white.withOpacity(0.7),
                        fontSize: 14.sp,
                        fontFamily:
                            GoogleFonts.poppins(
                              fontWeight: FontWeight.w400,
                            ).fontFamily,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),

          SizedBox(height: 20.h),

          // 关注和聊天按钮
          Row(
            children: [
              Expanded(child: _buildFollowButton(user)),
              SizedBox(width: 12.w),
              Expanded(child: _buildChatButton(user)),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建关注按钮
  Widget _buildFollowButton(UserDataEntity user) {
    return StoreConnector<AppState, bool>(
      converter: (store) {
        final currentUser = store.state.userState.activeUser;
        if (currentUser == null) return false;

        final followManager = serviceLocator<ReduxFollowManager>();
        return followManager.isFollowing(currentUser.uniqueId, user.uniqueId);
      },
      builder: (context, isFollowing) {
        return Container(
          height: 38.h,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                Colors.white.withOpacity(0.2),
                Colors.white.withOpacity(0.1),
              ],
            ),
            borderRadius: BorderRadius.circular(24.r),
            border: Border.all(color: Colors.white.withOpacity(0.3), width: 1),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                isFollowing
                    ? 'assets/images/followed.png'
                    : 'assets/images/follow.png',
                width: 20.w,
                height: 20.w,
              ),
              SizedBox(width: 8.w),
              Text(
                isFollowing ? 'Followed' : 'Follow',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w500,
                  fontFamily:
                      GoogleFonts.poppins(
                        fontWeight: FontWeight.w500,
                      ).fontFamily,
                ),
              ),
            ],
          ),
        ).inkWell(
          onTap: () {
            _handleFollowAction(user, isFollowing);
          },
        );
      },
    );
  }

  /// 构建聊天按钮
  Widget _buildChatButton(UserDataEntity user) {
    return Container(
      height: 38.h,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Colors.white.withOpacity(0.2),
            Colors.white.withOpacity(0.1),
          ],
        ),
        borderRadius: BorderRadius.circular(24.r),
        border: Border.all(color: Colors.white.withOpacity(0.3), width: 1),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset('assets/images/chat2.png', width: 20.w, height: 20.w),
          SizedBox(width: 8.w),
          Text(
            'Chat',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16.sp,
              fontWeight: FontWeight.w500,
              fontFamily:
                  GoogleFonts.poppins(fontWeight: FontWeight.w500).fontFamily,
            ),
          ),
        ],
      ),
    ).inkWell(
      onTap: () {
        _handleChatAction(user);
      },
    );
  }

  /// 构建内容标签页
  Widget _buildContentTabs() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 20.h),
      child: Row(
        children: [
          _buildTabButton('Release', 0),
          SizedBox(width: 24.w),
          _buildTabButton('Like', 1),
        ],
      ),
    );
  }

  /// 构建标签按钮
  Widget _buildTabButton(String title, int index) {
    final isSelected = _selectedTabIndex == index;
    return Text(
      title,
      style: TextStyle(
        color: isSelected ? Colors.white : Colors.white.withOpacity(0.5),
        fontSize: 20.sp,
        fontWeight: isSelected ? FontWeight.w700 : FontWeight.w400,
        fontFamily:
            GoogleFonts.nunito(
              fontWeight: isSelected ? FontWeight.w800 : FontWeight.w800,
            ).fontFamily,
      ),
    ).inkWell(
      onTap: () {
        setState(() {
          _selectedTabIndex = index;
        });
        _tabController.animateTo(index);
      },
    );
  }

  /// 构建内容区域
  Widget _buildContentArea() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: IndexedStack(
        index: _selectedTabIndex,
        children: [_buildReleaseContent(), _buildLikeContent()],
      ),
    );
  }

  /// 构建发布内容
  Widget _buildReleaseContent() {
    return StoreConnector<AppState, List<SocialPostEntity>>(
      converter: (store) {
        final currentUser = store.state.userState.activeUser;
        if (currentUser == null) return [];

        return store.state.socialState.postCollection
            .where((post) => post.authorId == currentUser.uniqueId)
            .toList();
      },
      builder: (context, userPosts) {
        if (userPosts.isEmpty) {
          return _buildEmptyState(
            'No posts yet',
            'Start sharing your moments!',
          );
        }

        return GridView.builder(
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            crossAxisSpacing: 12.w,
            mainAxisSpacing: 12.h,
            childAspectRatio: 157 / 250,
          ),
          itemCount: userPosts.length,
          itemBuilder: (context, index) {
            return _buildPostItem(userPosts[index]);
          },
        );
      },
    );
  }

  /// 构建点赞内容
  Widget _buildLikeContent() {
    return StoreConnector<AppState, List<SocialPostEntity>>(
      converter: (store) {
        final currentUser = store.state.userState.activeUser;
        if (currentUser == null) return [];

        return store.state.socialState.postCollection
            .where((post) => post.likedUserIds.contains(currentUser.uniqueId))
            .toList();
      },
      builder: (context, likedPosts) {
        if (likedPosts.isEmpty) {
          return _buildEmptyState(
            'No liked posts',
            'Like posts to see them here!',
          );
        }

        return GridView.builder(
          padding: EdgeInsets.zero,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            crossAxisSpacing: 12.w,
            mainAxisSpacing: 12.h,
            childAspectRatio: 157 / 250,
          ),
          itemCount: likedPosts.length,
          itemBuilder: (context, index) {
            return _buildPostItem(likedPosts[index]);
          },
        );
      },
    );
  }

  /// 构建单个帖子项
  Widget _buildPostItem(SocialPostEntity post) {
    final isImage =
        post.mediaType == PostMediaType.image && post.mediaUrl != null;
    final isVideo =
        post.mediaType == PostMediaType.video && post.thumbnailUrl != null;
    final viewCount = _getFixedViewCount(post.postId); // 基于ID的固定浏览次数

    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        color: Colors.white.withOpacity(0.1),
        border: Border.all(color: Colors.white.withOpacity(0.2), width: 1),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 图片/视频区域
          Expanded(
            flex: 4,
            child: Padding(
              padding: EdgeInsets.all(5.w),
              child: Stack(
                children: [
                  // 媒体内容
                  Container(
                    width: double.infinity,
                    height: double.infinity,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(12.r),
                        topRight: Radius.circular(12.r),
                      ),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(12.r),
                        topRight: Radius.circular(12.r),
                      ),
                      child:
                          isImage
                              ? Image.asset(
                                post.mediaUrl!,
                                width: double.infinity,
                                height: double.infinity,
                                fit: BoxFit.cover,
                                errorBuilder: (context, error, stackTrace) {
                                  return Container(
                                    color: Colors.grey[800],
                                    child:
                                        Icon(
                                          Icons.image,
                                          size: 32.w,
                                          color: Colors.grey[600],
                                        ).center(),
                                  );
                                },
                              )
                              : isVideo
                              ? Image.asset(
                                post.thumbnailUrl!,
                                width: double.infinity,
                                height: double.infinity,
                                fit: BoxFit.cover,
                                errorBuilder: (context, error, stackTrace) {
                                  return Container(
                                    color: Colors.grey[800],
                                    child:
                                        Icon(
                                          Icons.video_library,
                                          size: 32.w,
                                          color: Colors.grey[600],
                                        ).center(),
                                  );
                                },
                              )
                              : Container(
                                color: Colors.grey[800],
                                child:
                                    Icon(
                                      Icons.image,
                                      size: 32.w,
                                      color: Colors.grey[600],
                                    ).center(),
                              ),
                    ),
                  ),

                  // 视频播放图标
                  if (post.mediaType == PostMediaType.video)
                    SizedBox(
                      width: double.infinity,
                      height: double.infinity,
                      child:
                          Icon(
                            Icons.play_circle_filled,
                            size: 40.w,
                            color: Colors.white.withOpacity(0.9),
                          ).center(),
                    ),

                  // 右上角举报按钮
                  Positioned(
                    top: 8.h,
                    right: 8.w,
                    child: Container(
                      width: 24.w,
                      height: 24.w,
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.3),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.more_vert,
                        size: 16.w,
                        color: Colors.white,
                      ).center().inkWell(
                        onTap: () {
                          _handlePostReport(post);
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),

          // 文字信息区域
          Expanded(
            flex: 2,
            child: Padding(
              padding: EdgeInsets.all(8.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 动态文字（最多两行）
                  Expanded(
                    child: Text(
                      post.content,
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.white,
                        fontFamily:
                            GoogleFonts.poppins(
                              fontWeight: FontWeight.w400,
                            ).fontFamily,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),

                  SizedBox(height: 8.h),

                  // 时间和浏览次数
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // 时间
                      Text(
                        _formatPostTime(post.publishTime),
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.white.withOpacity(0.7),
                          fontFamily:
                              GoogleFonts.poppins(
                                fontWeight: FontWeight.w400,
                              ).fontFamily,
                        ),
                      ),

                      // 浏览次数
                      Row(
                        children: [
                          Image.asset(
                            'assets/images/eye.png',
                            width: 16.w,
                            height: 16.w,
                          ),
                          SizedBox(width: 4.w),
                          Text(
                            '$viewCount',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: Colors.white.withOpacity(0.7),
                              fontFamily:
                                  GoogleFonts.poppins(
                                    fontWeight: FontWeight.w400,
                                  ).fontFamily,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    ).inkWell(
      onTap: () {
        _handlePostTap(post);
      },
    );
  }

  /// 处理帖子点击
  void _handlePostTap(SocialPostEntity post) {
    // 检查登录状态
    final store = StoreProvider.of<AppState>(context);
    final currentUser = store.state.userState.activeUser;

    if (currentUser == null) {
      VamosLoginRequiredDialog.showLoginRequiredDialog(context);
      return;
    }

    // 跳转到帖子详情页面
    Navigator.of(context).push(
      TransitionPageRoute(
        builder: (context) => VamosSocialDetailInterface(post: post),
        transitionAnimation: BrushStrokeTransition(
          direction: TransitionDirection.right,
          colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
        ),
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState(String title, String subtitle) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 60.h),
      child: Column(
        children: [
          Image.asset(
            'assets/images/empty.png',
            width: 80.w,
            height: 80.w,
            fit: BoxFit.contain,
          ),
          SizedBox(height: 16.h),
          Text(title)
              .fontSize(16.sp)
              .textColor(Colors.white.withOpacity(0.7))
              .fontFamily(
                GoogleFonts.poppins(fontWeight: FontWeight.w500).fontFamily!,
              ),
          SizedBox(height: 8.h),
          Text(subtitle)
              .fontSize(14.sp)
              .textColor(Colors.white.withOpacity(0.5))
              .fontFamily(
                GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily!,
              ),
        ],
      ),
    );
  }

  /// 格式化发布时间
  String _formatPostTime(DateTime publishTime) {
    final hour = publishTime.hour.toString().padLeft(2, '0');
    final minute = publishTime.minute.toString().padLeft(2, '0');
    return '$hour:$minute';
  }

  /// 获取固定的浏览次数（基于ID生成）
  int _getFixedViewCount(String postId) {
    // 使用postId的hashCode来生成固定的随机数
    final random = Random(postId.hashCode);
    return random.nextInt(500) + 50; // 50-549之间的固定值
  }

  /// 处理帖子举报
  void _handlePostReport(SocialPostEntity post) {
    showVamosReportDialog(
      context: context,
      title: 'Report Post',
      subtitle: 'Please select a reason for reporting this post.',
      onReportSubmitted: (VamosReportOption option) {
        _deletePostAndExit(post);
      },
    );
  }

  /// 删除动态并返回
  void _deletePostAndExit(SocialPostEntity post) async {
    try {
      final socialManager = serviceLocator<ReduxSocialManager>();
      final success = await socialManager.deletePost(post.postId);
      if (success) {
        NotificationUtils.showSuccess(
          context,
          message: 'You won\'t see this again.',
        );
        // 不需要返回，因为列表会自动更新
      } else {
        NotificationUtils.showError(context, message: 'Failed to report post.');
      }
    } catch (e) {
      NotificationUtils.showError(context, message: 'Error reporting post: $e');
    }
  }
}
